package com.fast.controller.login;

import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.extension.api.R;
import com.fast.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author hjw
 * @since 2022年03月24日 10:17:00
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {
    private static ConcurrentHashMap<String,Object> result =new ConcurrentHashMap<>();

    @ApiOperation("注册用户")
    @GetMapping("/register")
    public R register(User user) {
        String gensalt = BCrypt.gensalt();
        String pwdSecuret = BCrypt.hashpw(user.getPwd(), gensalt);
        user.setPwd(pwdSecuret);
        result.put(user.getLoginName(),user);
        for (String key : result.keySet()) {
            System.out.println("key-"+key+"======="+"value-"+result.get(key));
        }
        return R.ok(result.get(user.getLoginName()));
    }

    @ApiOperation("用户登录")
    @GetMapping("/login")
    public R login(User user) {
        for (String key : result.keySet()) {
            System.out.println("key-"+key+"======="+"value-"+result.get(key));
        }
        User userResult = (User) result.get(user.getLoginName());
        boolean checkpw = BCrypt.checkpw(user.getPwd(), userResult.getPwd());
        if (checkpw) {
            Map<String,Object> payload = new HashMap<>();
            payload.put("username",user.getLoginName());
            payload.put("exp",new Date(System.currentTimeMillis()+5000));
            String token = JWTUtil.createToken(payload, "ceshi".getBytes());
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("token",token);
            return R.ok(resultMap);
        }else {
            return R.failed("用户名或密码错误");
        }
    }

    @ApiOperation("测试token访问")
    @GetMapping("/test")
    public R test(User user) {
        return R.ok("测试token");
    }

    public static void main(String[] args) throws InterruptedException {
        Map<String, Object> info = new HashMap<>();
        info.put("userId","23234234");
        info.put("username","张三");
        String token = JwtUtil.create(info);
        JSONObject jsonObject = JwtUtil.parse("eyJ0eXAiOiJKV1QiLCJraWQiOiJlNGJjZTc0ZC1lOTIwLTQ5OTgtYWRmMy02YmI2ZGRlMzIyZTUiLCJjdHkiOiJ1c2VyIiwiYWxnIjoiSFMyNTYifQ.eyJleHAiOjE2NDgxMTY2MjgsInVzZXJJZCI6IjIzMjM0MjM0IiwianRpIjoiNjlhNmU2NGItYjdkMS00NzQxLTlhZWYtMmRhZTA2ZjdhZDkzIiwidXNlcm5hbWUiOiLlvKDkuIkifQ.1aMkCO1FPi-sjddMXTeCwf5v7AvV3Ey_QtZMgOiWZFM");
        System.out.println("jsonObject = " + jsonObject);
    }
}
